from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
from utils.pageTool import get_objects_page
from .models import *

#定义推荐商品的装饰器
def wrapper_recommend_goods_cookie(func):
    def _wrapper(detailview,request,goods_id,*args,**kwargs):
        #先从cookie获取存储的已浏览过的所有商品
        key = 'recommend_goods'
        raw_remcommend_goods = request.COOKIES.get(key,'')    #'5 6 7 8'保存的是商品id号，中间用空格去分隔
        #将字符串分割成列表
        goods_list = [item for item in raw_remcommend_goods.split() if item.strip()]
        #推荐算法：
        #1.不能是当前的商品
        #2.和当前的商品类别要一致
        #3.取前四个
        recommend_goods = [Goods.objects.get(id=gid) for gid in goods_list if gid != goods_id and
                           Goods.objects.get(id=goods_id).category_id == Goods.objects.get(id=gid).category_id][:4]
        #调用被修饰的函数
        response = func(detailview,request,goods_id,recommend_goods,*args,**kwargs)
        #将当前浏览的商品添加到cookie中的推荐商品中
        goods_id = str(goods_id)
        if goods_id not in goods_list:
            goods_list.append(goods_id)   #没有就添加
        else:
            goods_list.remove(goods_id)   #有提高优先级
            goods_list.insert(0,goods_id)

        #将推荐商品保存到cookie中
        response.set_cookie(key,' '.join(goods_list),max_age=60*60*24*3)
        #返回响应对象
        return response
    #返回内部函数
    return _wrapper

# Create your views here.
#使用视图类的方式去定义视图函数
class TestView(View):
    #通过get方法去响应get请求
    def get(self,request,pagenum=1):
        object_list = Goods.objects.all()
        page,goodses = get_objects_page(object_list,pagenum,5)
        page_range = page.paginator.page_range
        return render(request,'test.html',{'goodses':goodses,'page_range':page_range})


class IndexView(View):
    categorys = Category.objects.all()   #获取所有的商品类别   类属性
    current_category_id = Category.objects.first().id    #当前类别的id号
    def get(self,request,category_id=None,pagenum=1):
        #处理一下类别的id号
        if category_id == None:
            current_cid = self.current_category_id
        else:
            current_cid = category_id
        #调用分页的工具函数
        pages,goods = get_objects_page(Goods.objects.filter(category_id=current_cid),pagenum)
        return render(request,'index.html',{'categorys':self.categorys,'current_cid':int(current_cid),'pages':pages,'goods':goods})

class DetailView(View):
    @wrapper_recommend_goods_cookie
    def get(self,request,goods_id,recommend_goods=[]):
        goods = Goods.objects.get(id=int(goods_id))
        return render(request,'detail.html',{'goods':goods,'recommend_goods':recommend_goods})